package com.zcsy.manage.web.system;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IMenuService;

/**
  * @ClassName: MenuController
  * @Description: 菜单控制层管理类
  * @author tanghan barbadosliy@163.com
  * @date 2015年2月1日 下午3:52:50
  *
  */
@Controller
@RequestMapping(value = "/menu")
public class MenuController {
    
    private static final int ALL_LEVEL = -1; //所有菜单等级

	@Autowired
	private IMenuService menuService;

	@Autowired
	private IDictService dictService;
	
	/**
	 * 分页获取数据列表
	 * @param pNo  起始页
	 * @param mName  菜单名
	 * @param url  本地路径
	 * @param level  菜单等级
	 * @param req 用户请求
	 * @return
	 */
	@RequestMapping(value="menuList" , method = RequestMethod.GET)
	public String getMenuListBySearchKey(Model model, Integer pNo, Integer pSize, String mName,
			String url, Short level, HttpServletRequest req){

	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
	    //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);
		Menu record = new Menu();
		
		if(level == null){
		    level = ALL_LEVEL;
		}
		
		//菜单名为不空字符串时，设置菜单名
		if(!"".equals(mName)){
		    record.setMenuName(mName);
		}
		
		//本地路径为不空字符串时，设置本地路径
        if(!"".equals(url)){
            record.setLocationURL(url); 
        }
		
		record.setMenuLevel(level); 
		record.setState(1);
		
		List<Menu> menuList = menuService.queryMenu(record);
		PageInfo<Menu> info = new PageInfo<Menu>(menuList);
		
		model.addAttribute("menuInfo", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("menuName", mName);
		model.addAttribute("url", url);
		model.addAttribute("level", level);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "system/menu/menuList";
	}
	
	/**
     * 根据角色获取数据列表
     * @param state  菜单状态
     * @param req 用户请求
     * @return
     */
    @RequestMapping(value="updateMenuStateById" , method = RequestMethod.GET)
    @ResponseBody
    public RequestJson updateMenuStateById(String menuId,int state,HttpServletRequest req){
        RequestJson result = new RequestJson();
        
        try {
            menuService.updateMenuState(menuId, state);
            
            result.setSuccess(true);
        }catch (Exception e) {
           e.printStackTrace();
           
           result.setMsg("操作异常");
           result.setSuccess(false);
        }
        
        return result;
    }
	
	/**
	 * 根据菜单状态获取数据列表
	 * @param state  菜单状态
	 * @param req 用户请求
	 * @return
	 */
	@RequestMapping(value="getMenuListByState" , method = RequestMethod.GET)
	@ResponseBody
	public List<Menu> getMenuListByState(@QueryParam("state") int state,
            @Context HttpServletRequest req){
		List<Menu> menus = menuService.getMenuByState(state);
		return menus;
	}
	
	@RequestMapping(value="getMenusByCache" , method = RequestMethod.GET)
	public List<Menu> getMenusByCache(
            @Context HttpServletRequest req){
	    User user = CommonService.getSessionUser();
		List<Menu> menus = menuService.getMenusByCache(user , Constants.SYSTEM_OPERATION_WEB);
		return menus;
	}
	
	
	/**
	 * 根据父菜单Id获取数据列表
	 * @param state  菜单状态
	 * @param req 用户请求
	 * @return
	 */
	@RequestMapping(value="getByPId" , method = RequestMethod.GET)
	public List<Menu> getMenuListByPId(@QueryParam("pid") String pid,@QueryParam("roleId") String roleId,
            @Context HttpServletRequest req){
		return menuService.getMenuByPId(pid , roleId);
	}
	
		
	/**
	 * 根据角色获取数据列表
	 * @param state  菜单状态
	 * @param req 用户请求
	 * @return
	 */
	@RequestMapping(value="getMenuListByRoleId" , method = RequestMethod.GET)
	public List<Menu> getMenuListByRoleId(@QueryParam("roleId") String roleId,
            @Context HttpServletRequest req){
		List<Menu> menus = menuService.queryMenuByRoleId(roleId);
		return menus;
	}
	
	/**
	 * Description: <br>
	 *   新增或修改菜单属性
	 * @param menuVo  菜单对象
	 * @param req 用户请求
	 * @return  请求结果
	 * @see com.framework.common.RequestJson
	 */
    @RequestMapping(value="editMenu" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateMenu(String id,String mName,Short mLevel,String mURL,Integer mOrder,String mPId,@Context HttpServletRequest req){
        RequestJson result = new RequestJson();
        Menu menuVo = new Menu();
        menuVo.setMenuName(mName);
        menuVo.setLocationURL(mURL);
        menuVo.setMenuLevel(mLevel);
        menuVo.setMenuOrder(mOrder);
        menuVo.setParentId(mPId == null ? "0" : mPId);
        
        try {
            if(id != null){
            	menuVo.setId(id);
                menuService.updateByPrimaryKey(menuVo);
            }else{
            	menuVo.setId(UniqueNumberUtils.get18UniqueNumber());
                menuService.insert(menuVo);
            }
            result.setSuccess(true);
        } catch (Exception e) {
        	e.printStackTrace();
            result.setMsg("操作失败");
        }
        return result;
    }
    
    /**
     * @Description 根据主键查询菜单
     * @param id
     *            菜单id
     * @return 查询的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "selectPK", method = RequestMethod.GET)
    public String selectByPrimaryKey(Model model,@QueryParam("id") String id) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.MENU_STATE_ENABLED);
                Menu menu = new Menu();
                short l = (short)(Constants.MENU_SELECT_NONE);
                menu.setMenuLevel(l);
                
                model.addAttribute("menu", menu);
            } else {
                Menu menu = menuService.getMenuById(id);
                model.addAttribute("menu", menu);
                Menu pmenu = menuService.getMenuById(menu.getParentId());
                model.addAttribute("pMenu", pmenu);
                Menu menuRecord = new Menu();
                if(menu.getMenuLevel() == 2){
                	 menuRecord.setMenuLevel((short)1);
                }else if(menu.getMenuLevel() == 3){
                	 menuRecord.setMenuLevel((short)2);
                }
                List<Menu> listMenu = menuService.queryMenu(menuRecord);
                model.addAttribute("listMenu",listMenu);
                model.addAttribute("type", Constants.EDIT_TYPE);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "system/menu/menuEdit";
    }
	
    @RequestMapping(value="getByLevel" , method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getByLevel(Short level,@Context HttpServletRequest req){
        RequestJson result = new RequestJson();
        Menu record = new Menu();
        record.setMenuLevel(level); 
        try {
            List<Menu> menuList = menuService.queryMenu(record);
            result.setObj(menuList);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        
        return result;
    }
    
    
    
	
}
